//
//  TranslationViewController.m
//  XhlTrip
//
//  Created by dlios on 15/9/28.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
////     http://fanyi.youdao.com/openapi.do?keyfrom=gogogo&key=1240475464&type=data&doctype=json&version=1.1&q=你好

#import "TranslationViewController.h"
#import "TranslationCell.h"
#import "LeaonWorking.h"
#import "iflyMSC/IFlyRecognizerView.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "iflyMSC/IFlySpeechUtility.h"
#import "iflyMSC/IFlyRecognizerView.h"
#import "iflyMSC/IFlyDataUploader.h"
#import "iflyMSC/IFlyContact.h"
#import "MobClick.h"
#import "AppContext.h"
#import "VNConstants.h"
#import "BackButton.h"
@interface TranslationViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,TranslationCellDelegate,IFlyRecognizerViewDelegate>
{
    BOOL _isEditingTitle;
}
@property (nonatomic, retain) UITableView *tabelView;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) UIScrollView *sc;
@property (nonatomic, retain) UITextField *text;
@property (nonatomic, retain) UIView *talkView;
@property (nonatomic, retain) UIView *textView;
@property (nonatomic, retain) UIButton *speak;
@property (nonatomic, retain) NSArray *launchArr;
@property (nonatomic, retain) NSArray *code;
@property (nonatomic, retain) UIButton *rightButton;
@property (nonatomic, assign) CGFloat a;
@property (nonatomic, retain) NSMutableArray *textArr;
@property (nonatomic, retain) NSMutableArray *textToArr;
@property (nonatomic, retain) NSString * launchCode;
@property (nonatomic, retain) NSString *toStr;
@property (nonatomic, retain) UIView *touchView;
@property (nonatomic, retain) UIButton *leftButton;
@property (nonatomic,retain)UIActivityIndicatorView *acticity;

@property (nonatomic,retain)IFlyRecognizerView *iflyRecognizerView;


@end

@implementation TranslationViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
      
        self.launchArr = [NSArray arrayWithObjects:@"中文",@"粤语",@"英语",@"日语",@"韩语",@"西班牙语",@"法语",@"泰语",@"阿拉伯语",@"俄罗斯语",@"葡萄牙语",@"德语",@"意大利语", nil];
        self.code = [NSArray arrayWithObjects:@"zh",@"yue",@"en",@"jp",@"kor",@"spa",@"fra",@"th",@"ara",@"ru",@"pt",@"de",@"it", nil];
        
        self.textArr = [NSMutableArray array];
        self.textToArr = [NSMutableArray array];
        
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSpeechRecognizer];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    
    [self addTableView];
    [self addtextFiled];
    [self addButton];
    [self addHeaderView];
   }
- (void)setupSpeechRecognizer
{
    NSString *initString = [NSString stringWithFormat:@"%@=%@", [IFlySpeechConstant APPID], kIFlyAppID];
    
    [IFlySpeechUtility createUtility:initString];
    _iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    _iflyRecognizerView.delegate = self;
    
    [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
}

- (void)addtextFiled
{
    self.textView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
    self.textView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:_textView];
    
    
    self.text = [[UITextField alloc]initWithFrame:CGRectMake(50, 7, self.view.frame.size.width - 57, 35)];
    self.text.returnKeyType = UIReturnKeySend;
    self.text.borderStyle = 3;
    self.text.placeholder = @"输入要翻译的内容";
    self.text.delegate = self;
    [self.textView addSubview:_text];

    
    
    self.speak = [UIButton buttonWithType:UIButtonTypeSystem];
    _speak.frame = CGRectMake(5, 5, 40, 40);
    _speak.layer.cornerRadius = 20;
    _speak.layer.masksToBounds = YES;
    [_speak setImage:[UIImage imageNamed:@"xiaoyuyin.png"] forState:UIControlStateNormal];
    [_speak addTarget:self action:@selector(speak:) forControlEvents:UIControlEventTouchUpInside];
    [self.textView addSubview:_speak];
    

    
}

- (void)speak:(UIButton *)button
{
    if (![AppContext appContext].hasUploadAddressBook) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"UploadABForBetter", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"ActionSheetCancel", @"") otherButtonTitles:NSLocalizedString(@"GotoUploadAB", @""), nil];
        [alertView show];
        [[AppContext appContext] setHasUploadAddressBook:YES];
        return;
    }
    
    
    
    self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
    [self hideKeyboard];
    [self startListenning];
    [MobClick event:kEventClickVoiceButton];

 
}
- (void)startListenning
{
    [_iflyRecognizerView start];
}
- (void)hideKeyboard
{
    if ([_text isFirstResponder]) {
        _isEditingTitle = YES;
        [_text resignFirstResponder];
    }
}
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    for (NSString *key in dic) {
        [result appendFormat:@"%@", key];
    }
    if (_isEditingTitle) {
//        _titleTextField.text = [NSString stringWithFormat:@"%@%@", _titleTextField.text, result];
    } else {
        _text.text = [NSString stringWithFormat:@"%@%@", _text.text, result];
        

        [self.textArr addObject:_text.text];
            
            self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);

            
            
            NSString *t = [self.text.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *str =[NSString stringWithFormat:@"http://openapi.baidu.com/public/2.0/bmt/translate?client_id=jxmbjt5uVUhh1e9VGN2AuyuY&from=zh&q=%@&to=%@",t,[self.code  objectAtIndex:self.launchCode.integerValue]];
            
            
            [LeaonWorking  netWorkingHanderGetGataWithUrl:str pathname:@"Fan" resultBlock:^(id result) {
                
                self.toStr = [[[result objectForKey:@"trans_result"] objectAtIndex:0]objectForKey:@"dst"];
                
                
                
                if (self.toStr != nil) {
                    
                [self.textToArr addObject:_toStr];
                }
                
                [self.tabelView reloadData];
                self.text.text = nil;
                [self.text resignFirstResponder];
                self.a++ ;
                [self.textArr addObject:self.text.text];
                [self.tabelView reloadData];
                self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
                
            }];
            
            
        
       

        
        
        
    }
}

- (void)addButton
{
    self.leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.leftButton.backgroundColor = [UIColor colorWithRed:131/ 255.f green:190/ 255.f blue:255 / 255.f alpha:0.5];
    [self.leftButton setTintColor:[UIColor whiteColor]];
     self.leftButton.frame = CGRectMake(0, 60, self.view.frame.size.width / 2 - 50, 50);
    [self.leftButton setTitle:@"自动检测" forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(jiance:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    
    
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightButton setTintColor:[UIColor whiteColor]];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    _rightButton.backgroundColor = [UIColor colorWithRed:131/ 255.f green:190/ 255.f blue:255 / 255.f alpha:0.5];
    _rightButton.frame = CGRectMake(self.view.frame.size.width / 2 + 50, 60, self.view.frame.size.width / 2 - 50, 50);

    [_rightButton addTarget:self action:@selector(chooseLaunch:) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setTitle:@"设置语言" forState:UIControlStateNormal];
    [self.view addSubview:_rightButton];
    
    
    
    UIImageView *change = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 50, 60, 100, 50)];
    
    change.backgroundColor = [UIColor colorWithRed:131 / 255.f green:190/ 255.f blue:255/ 255.f alpha:0.5];
    [self.view addSubview:change];
    
    
    
}

- (void)addTableView
{
    self.tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    UIImageView *imageV = [[UIImageView alloc]init];
    imageV.userInteractionEnabled = YES;
    imageV.image = [UIImage imageNamed:@"4.png"];
    
    [self.tabelView setBackgroundView:imageV];
    
    
    
    
    UIBlurEffect *ef = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effV = [[UIVisualEffectView alloc]initWithEffect:ef];

    effV.frame = [UIScreen mainScreen].bounds;
    [imageV addSubview:effV];
 
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 115)];
    view.backgroundColor = [UIColor clearColor];
    self.tabelView.tableHeaderView = view;
    
    
    
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tabelView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TranslationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[TranslationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        
        
    }
    
    
    if (self.textToArr.count == indexPath.row + 1) {
        
        cell.to.text = [self.textToArr objectAtIndex:indexPath.row]; ;
    }
    cell.from.text = [self.textArr objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delet.tag = indexPath.row + 1;
    cell.bound.tag = indexPath.row + 1;
    cell.delegate = self;
    return cell;
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.a;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (void)jiance:(UIButton *)button
{
    button.selected = !button.selected;
    [self.text resignFirstResponder];
    self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
    
    
    
    if (button.selected) {
        
        
        [UIView animateWithDuration:0.3 animations:^{
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.backgroundColor = [UIColor colorWithRed:131.f / 255.f green:190.f / 255.f blue:255.f / 255.f alpha:1];
                
                [button addTarget:self action:@selector(choose:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:button];
         
            
            
            
        }];
        
        
        
        
    }else{
        
        

    }
    

}
- (void)chooseLaunch:(UIButton *)button
{
    
    button.selected = !button.selected;
    [self.text resignFirstResponder];
    self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
    if (button.selected) {
        
        
        [UIView animateWithDuration:0.3 animations:^{
            self.sc = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 50, 115, self.view.frame.size.width / 2, 600)];
             [self.view addSubview:_sc];
            for (int i = 0; i < 13; i ++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                
               
                button.frame = CGRectMake(0, i * 31, 133, 30);
                button.tag = i + 1;
                [button setTitle:[self.launchArr objectAtIndex:i] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.backgroundColor = [UIColor colorWithRed:131.f / 255.f green:190.f / 255.f blue:255.f / 255.f alpha:0.5];
                
                [button addTarget:self action:@selector(choose:) forControlEvents:UIControlEventTouchUpInside];
                [self.sc addSubview:button];
                
            }
            
            
           
        }];
        
        
        
        
    }else{
        
        
        [self.sc removeFromSuperview];
    }
    
}
- (void)choose:(UIButton *)button
{
    
    NSInteger t = button.tag - 1;
    NSString *str = [NSString stringWithFormat:@"%ld",(long)t];
    
    self.launchCode = str ;
    
    
    [self.sc removeFromSuperview];
    [self.rightButton setTitle:button.titleLabel.text forState:UIControlStateNormal];
    self.rightButton.selected = NO;

}
- (void)gotoBound:(UIButton *)button
{
    
   self.touchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.touchView.backgroundColor = [UIColor purpleColor];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(200, 350, 150, 350)];
    lable.text = [self.textToArr objectAtIndex:button.tag - 1];
    
    [self.touchView addSubview:lable];
    [self.view addSubview:_touchView];
}


-  (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch.view == _touchView) {
        
        
        [_touchView removeFromSuperview];
    }
    if (touch.view == [[self.tabelView subviews] lastObject]) {
        
        [self.text resignFirstResponder];
    }
}
- (void)gotoDelete:(UIButton *)button
{
    [self.textArr removeObjectAtIndex:button.tag - 1];
    [self.textToArr removeObjectAtIndex:button.tag - 1];
    self.a = self.a - 1;
    [self.tabelView reloadData];
    
    
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (![textField.text isEqualToString:@""] ) {
        
   
    self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
#pragma 小圈圈 - mark
        
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.5;
    [self.view addSubview:view];
    [view release];
    
    self.acticity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32 , 32 )];
    self.acticity.center = view.center;
    self.acticity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [view addSubview:self.acticity];
    [self.acticity startAnimating];
    [_acticity release];
    
    
    
    NSString *t = [self.text.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if (textField.text != nil) {
            
            [self.textArr insertObject:textField.text atIndex:0];
        }
    NSString *str =[NSString stringWithFormat:@"http://openapi.baidu.com/public/2.0/bmt/translate?client_id=jxmbjt5uVUhh1e9VGN2AuyuY&from=zh&q=%@&to=%@",t,[self.code  objectAtIndex:self.launchCode.integerValue]];
    
    
    [LeaonWorking  netWorkingHanderGetGataWithUrl:str pathname:@"Fan" resultBlock:^(id result) {
        
        self.toStr = [[[result objectForKey:@"trans_result"] objectAtIndex:0]objectForKey:@"dst"];
        [self.textToArr insertObject:_toStr atIndex:0];
        [self.tabelView reloadData];
        
        
        [self.acticity stopAnimating];
        [view removeFromSuperview];

        
    }];
    
    
    [self.text resignFirstResponder];
    self.a++ ;
    [self.tabelView reloadData];
    self.textView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
         }
    return YES;

}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 

    
    self.speak.selected = NO;
    [self.talkView removeFromSuperview];
    [UIView animateWithDuration:0.2 animations:^{
        self.textView.frame = CGRectMake(0, 360, self.view.frame.size.width, 50);
    }];
    
    
    
    return YES;
    
}




- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    
    [textField resignFirstResponder];
         self.text.text = nil;
    return YES;
}
- (void)addHeaderView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
//    view.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.2];
    view.backgroundColor = [UIColor colorWithRed:131/ 255.f green:190/ 255.f blue:255 / 255.f alpha:0.5];
    [self.view addSubview:view];
    
    BackButton *button = [[BackButton alloc]init];
    button.frame = CGRectMake(5, 25, 100, 30);
    [button setTintColor:[UIColor whiteColor]];
    button.backImage .image = [UIImage imageNamed:@"houtui.png"];
    button.backTitle.text = @"语音翻译";
    [button addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    
    
    
}
-(void)back:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
